package com.bricker.laboratorymanagement.business.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bricker.laboratorymanagement.business.dao.SysGroupMapper;
import com.bricker.laboratorymanagement.business.dao.SysUserMapper;
import com.bricker.laboratorymanagement.business.entity.SysGroup;
import com.bricker.laboratorymanagement.business.entity.SysUser;
import com.bricker.laboratorymanagement.business.model.ResultLogin;
import com.bricker.laboratorymanagement.business.model.UserModel;
import com.bricker.laboratorymanagement.business.model.UserSelectModel;
import com.bricker.laboratorymanagement.business.service.SysUserService;
import com.bricker.laboratorymanagement.utils.MD5Util;
import com.bricker.laboratorymanagement.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysGroupMapper groupMapper;

    @Override
    public ResultLogin login(SysUser loginUser) {
        ResultLogin resultLogin =new ResultLogin();
        String userName =loginUser.getUserName();
        SysUser user= super.getOne(Wrappers.<SysUser>lambdaQuery()
                .eq(SysUser::getUserName,userName)
                .eq(SysUser::getDelFlag,"0"));

        if(user==null){
            resultLogin.setCode("10001");
            resultLogin.setMessage("用户不存在");
        }else{
            boolean bool= MD5Util.passwordIsTrue(loginUser.getPassword(),user.getPassword());
            if(bool){
                String token= TokenUtil.sign(user);
                if(token != null){
                    resultLogin.setCode("10000");
                    resultLogin.setMessage("认证成功");
                    resultLogin.setToken(token);
                }
            }else{
                resultLogin.setCode("10002");
                resultLogin.setMessage("密码错误");
            }
        }
        return resultLogin;
    }


    @Override
    public Map<String, Object> register(SysUser registerUser) {
        List<SysUser> list= super.list(Wrappers.<SysUser>lambdaQuery()
                .eq(SysUser::getUserName,registerUser.getUserName())
                .eq(SysUser::getDelFlag,"0"));
        Map<String,Object> map =new HashMap<>();
        if(list.size()==0){
            registerUser.setDelFlag("0");
            registerUser.setCreateTime(LocalDateTime.now());
            registerUser.setPassword(MD5Util.string2MD5(registerUser.getPassword()));
            registerUser.setUserType("1");
            if(super.save(registerUser)){
                map.put("code","20000");
                map.put("message","注册成功");
            };
        }else{
            map.put("code","20001");
            map.put("message","账户已存在");
        }
        return map;
    }

    @Override
    public Map<String,Object>  updateUser(SysUser updateUser) {
        Map<String,Object> map =new HashMap<>();

        if(StringUtils.isNotEmpty(updateUser.getPassword())){
            updateUser.setPassword(MD5Util.string2MD5(updateUser.getPassword()));
        }
        int i = sysUserMapper.updateById(updateUser);
        if(i > 0){
            map.put("code","20000");
            map.put("message","修改成功");
        }
        return map;
    }
// 测试修改
    @Override
    public Page<UserModel> getUserByPage(UserSelectModel userSelectModel) {
        Page<UserModel> page=new Page<>(userSelectModel.getCurrent(),userSelectModel.getSize());
        return page.setRecords(sysUserMapper.getUserByPage(page,userSelectModel));
    }

    @Override
    public UserModel getCurrentUser(Long id) {
        return sysUserMapper.getCurrentUser(id);
    }

    @Override
    public void saveOrUpdateUser(Long uId, List<SysUser> users) {
        if(!CollectionUtils.isEmpty(users)){
            for (SysUser user : users) {
                SysUser queryUser = sysUserMapper.selectById(user.getId());
                Long id=user.getId();
                Long groupId = user.getGroupId();
                if(id==null){
                    user.setCreateBy(uId);
                    user.setCreateTime(LocalDateTime.now());
                    user.setDelFlag("0");
                }
                // 退出小组
                if (groupId != null && groupId == 0) {

                    SysGroup group = groupMapper.selectById(queryUser.getGroupId());
                    String[] oldIds = group.getUserIds().split(",");
                    String newIds = "";
                    for (String oldId : oldIds) {
                        if (!oldId.equals(id.toString())) {
                            newIds += (oldId + ",");
                        }
                    }
                    if("".equals(newIds)) {
                        // 小组没有人
                        group.setDelFlag("1");
                        groupMapper.updateById(group);
                    } else {
                        group.setUserIds(newIds.substring(0,newIds.length()-1));//去掉最后一个,
                        groupMapper.updateById(group);
                    }
                }

                user.setUpdateBy(uId);
                user.setUpdateTime(LocalDateTime.now());
            }
            super.saveOrUpdateBatch(users);
        }
    }
}
